package com.gombe.credit.app.ui.activity

import android.annotation.SuppressLint
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.GridLayoutManager
import com.gombe.credit.app.R
import com.gombe.credit.app.base.app.GombeCreditActivityStackManager
import com.gombe.credit.app.common.CommonActivity
import com.gombe.credit.app.configs.GombeCreditApiPath
import com.gombe.credit.app.configs.GombeCreditApiUrl
import com.gombe.credit.app.configs.GombeCreditApiUrl.addCommonParams
import com.gombe.credit.app.databinding.ActGombeCreditMainBinding
import com.gombe.credit.app.event.GombeCreditEventData
import com.gombe.credit.app.request.IHttpCallback
import com.gombe.credit.app.ui.adapter.AdapterGombeCreditMainTab
import com.gombe.credit.app.ui.dialog.DialogGombeCreditUpdate
import com.gombe.credit.app.ui.fragment.FragmentGombeCreditHome
import com.gombe.credit.app.ui.fragment.FragmentGombeCreditRepay
import com.gombe.credit.app.ui.fragment.FragmentGombeCreditStatus
import com.gombe.credit.app.ui.fragment.FragmentGombeCreditUserCenter
import com.gombe.credit.app.utils.GombeCreditDateUtil
import com.gombe.credit.app.utils.GombeCreditTitleBarUtil
import com.gombe.credit.app.utils.helper.GombeCreditConfigsHelper
import com.gombe.credit.app.utils.helper.GombeCreditProcessHelper
import com.gombe.credit.app.utils.helper.GombeCreditUpdateHelper
import com.gombe.credit.app.utils.helper.TestDataLibInvoke
import com.gombe.credit.app.utils.log.GombeCreditLogger
import com.gombe.credit.app.utils.shared.GombeCreditSharedHelper
import com.gombe.credit.app.utils.shared.GombeCreditSharedKey
import com.gombe.credit.lib.adapter.GombeCreditOnItemChildClickListener
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * GombeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/28 14:39
 * @Annotation：主页
 */
class ActGombeCreditMain: CommonActivity(){
    lateinit var binding: ActGombeCreditMainBinding

    //首页
    private var mainHomeFragment: FragmentGombeCreditHome? = null
    //审核中、放款中、已拒绝
    private var mainStatusFragment: FragmentGombeCreditStatus? = null
    //待还款
    private var mainRepayFragment: FragmentGombeCreditRepay? = null
    //个人中心
    private var mainMenuFragment: FragmentGombeCreditUserCenter? = null

    //定义tab的每个页面
    private val tabList = arrayListOf<JSONObject>()

    private var tabAdapter: AdapterGombeCreditMainTab? = null
    var eventRemark = ""
    private var selectedTabIndex = 0

    private var updateHelper: GombeCreditUpdateHelper? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功

        } else {

        }
    }

    override fun takeGombeCreditRootView(): View {
        binding = ActGombeCreditMainBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initGombeCreditView() {
        setBackExit(true)
        GombeCreditTitleBarUtil.setStatusBarLightMode(this@ActGombeCreditMain, true)
        initGombeCreditMainTabGridView()
        //移除流程接口数据
        GombeCreditSharedHelper.deleteGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_PROCESS)
    }

    override fun initGombeCreditListener() {
    }

    override fun takeGombeCreditData() {
        showGombeCreditLoading()
        loadGombeCreditMainTabList()

        //是否有新版本
        val isUpdate = GombeCreditConfigsHelper.isGombeCreditUpdate()
        if (isUpdate){
            showGombeCreditUpdateDialog()
        }
    }

    /**
     * 初始化Tab列表
     */
    private fun initGombeCreditMainTabGridView() {
        val layoutManager = GridLayoutManager(this,2)
        binding.mainTabListView.layoutManager = layoutManager
        tabAdapter = AdapterGombeCreditMainTab(binding.mainTabListView)
        binding.mainTabListView.adapter = tabAdapter
        binding.mainTabListView.itemAnimator = DefaultItemAnimator()
        tabAdapter?.setOnItemChildClickListener(GombeCreditOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.tabItemLayout) {//切换item
                checkGombeCreditMainTab(position)
            }
        })
    }

    /**
     * 加载Tablist
     */
    private fun loadGombeCreditMainTabList(){
        val tabIconNormalList = arrayListOf(R.mipmap.gombe_credit_image_tab_home_normal, R.mipmap.gombe_credit_image_tab_menu_normal)
        val tabIconSelectedList = arrayListOf(R.mipmap.gombe_credit_image_tab_home_selected, R.mipmap.gombe_credit_image_tab_menu_selected)
        val tabTitleList = arrayListOf(R.string.gombe_credit_main_tab_home, R.string.gombe_credit_main_tab_menu)
        tabList.clear()
        //tab
        for (i in 0 until tabTitleList.size) {
            val tabObj = JSONObject()
            tabObj.put("tabId", i)
            tabObj.put("tabNormalIcon", tabIconNormalList[i])
            tabObj.put("tabSelectedIcon", tabIconSelectedList[i])
            tabObj.put("tabTitle", getString(tabTitleList[i]))
            tabObj.put("isSelect", false)
            tabList.add(tabObj)
        }
        tabAdapter?.data = tabList
        checkGombeCreditMainTab(0)
    }

    /**
     * 切换page
     */
    @SuppressLint("NotifyDataSetChanged")
    private fun checkGombeCreditMainTab(position: Int){
        selectedTabIndex = position
        tabAdapter?.let {
            for (i in 0..< it.data.size){
                val item = it.getItem(i)
                item.put("isSelect", position == i)
            }
            it.notifyDataSetChanged()
        }

        when(position){
            0 -> {
                if (GombeCreditProcessHelper.takeGombeCreditProcessData() != null){
                    checkGombeCreditMainShowPage()
                }
                showGombeCreditLoading()
                loadGombeCreditProcessAction()
            }
            else -> {
                showGombeCreditMainMenuPage()
            }
        }
    }

    /**
     * 隐藏所有的页面
     */
    private fun hideGombeCreditAllFragment() {
        mainHomeFragment?.let {
            hideContainerFragement(it)
        }
        mainStatusFragment?.let {
            hideContainerFragement(it)
        }
        mainRepayFragment?.let {
            hideContainerFragement(it)
        }
        mainMenuFragment?.let {
            hideContainerFragement(it)
        }
    }

    /**
     * 检查首页显示内容
     */
    private fun checkGombeCreditMainShowPage(){
        //防止网络延迟，切换到其它Tab依然显示首页bug
        if (selectedTabIndex != 0){
            return
        }
        //待还款
        val isRepay = GombeCreditProcessHelper.isGombeCreditRepay()
        if (isRepay){
            showGombeCreditMainRepayPage()
            return
        }
        //审核中 || 放款中 || 已拒绝
        val isReviewing = GombeCreditProcessHelper.isGombeCreditReviewing()
        val isDisbursing = GombeCreditProcessHelper.isGombeCreditDisbursing()
        val isRejected = GombeCreditProcessHelper.isGombeCreditRejected()
        if (isReviewing or isDisbursing or isRejected){
            showGombeCreditMainStatusPage()
            return
        }
        //显示主页
        showGombeCreditMainHomePage()
    }

    /**
     * 显示首页
     */
    private fun showGombeCreditMainHomePage(){
        hideGombeCreditAllFragment()
        if (mainHomeFragment == null) {
            mainHomeFragment = FragmentGombeCreditHome()
        }
        mainHomeFragment?.let {
            if (it.isAdded) {
                showContainerFragement(it)
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
                //首次延时发送加载数据通知
                lifecycleScope.launch {
                    delay(200)
                    publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_DATA_REFRESH))
                }
            }
        }
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, false)
    }

    /**
     * 显示贷款状态：审核中、放款中、已拒绝
     */
    private fun showGombeCreditMainStatusPage(){
        hideGombeCreditAllFragment()
        if (mainStatusFragment == null) {
            mainStatusFragment = FragmentGombeCreditStatus()
        }
        mainStatusFragment?.let {
            if (it.isAdded) {
                showContainerFragement(it)
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
                //首次延时发送加载数据通知
                lifecycleScope.launch {
                    delay(200)
                    publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_DATA_REFRESH))
                }
            }
        }
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)
    }

    /**
     * 待还款
     */
    private fun showGombeCreditMainRepayPage(){
        hideGombeCreditAllFragment()
        if (mainRepayFragment == null) {
            mainRepayFragment = FragmentGombeCreditRepay()
        }
        mainRepayFragment?.let {
            if (it.isAdded) {
                showContainerFragement(it)
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
                //首次延时发送加载数据通知
                lifecycleScope.launch {
                    delay(200)
                    publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_DATA_REFRESH))
                }
            }
        }
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)
    }

    /**
     * 显示个人中心
     */
    private fun showGombeCreditMainMenuPage(){
        hideGombeCreditAllFragment()
        if (mainMenuFragment == null) {
            mainMenuFragment = FragmentGombeCreditUserCenter()
        }
        mainMenuFragment?.let {
            if (it.isAdded) {
                showContainerFragement(it)
            } else {
                addContainerFragement(R.id.mainContentLayout, it)
            }
        }
        GombeCreditTitleBarUtil.setStatusBarLightMode(this, true)
    }

    /**
     * 需要校验手机号
     */
    fun showGombeCreditMainMustCheckMobilePage() {
        //当前栈顶是 手机号校验页面 不重复跳转
        if (GombeCreditActivityStackManager.isCurrentActivity(ActGombeCreditVerifyMobile::class.java)){
            return
        }
        //是否是审核账号
        val isAdmin = GombeCreditSharedHelper.takeGombeCreditSharedBoolean(GombeCreditSharedKey.GOMBECREDIT_IS_CONFIG_ACCOUNT)
        if(isAdmin) {//审核账号，直接不走校验
            return
        }
        ActGombeCreditVerifyMobile.start(this)
    }

    /**
     * 版本更新Dialog
     */
    private fun showGombeCreditUpdateDialog(){
        val lastShowTime = GombeCreditSharedHelper.takeGombeCreditSharedString(GombeCreditSharedKey.GOMBECREDIT_UPDATE_VERSION_LAST_TIME)
        if (lastShowTime.isNotEmpty() && GombeCreditDateUtil.isSameDay(lastShowTime.toLong(),System.currentTimeMillis())){
            return
        }
        GombeCreditSharedHelper.addGombeCreditSharedData(GombeCreditSharedKey.GOMBECREDIT_UPDATE_VERSION_LAST_TIME,"${System.currentTimeMillis()}")
        val updateDialog = DialogGombeCreditUpdate(this,"Main page",object : DialogGombeCreditUpdate.IDialogCallback{
            override fun onUpdateClick() {
                try {
                    if (updateHelper == null){
                        updateHelper = GombeCreditUpdateHelper(activity = this@ActGombeCreditMain, forceUpdate = false, updateLauncher)
                    }
                    updateHelper?.checkAndStartUpdate { }
                } catch (e: Exception) {

                }
            }
        })
        updateDialog.show()
    }

    override fun onGombeCreditPublishEvent(event: GombeCreditEventData) {
        super.onGombeCreditPublishEvent(event)
        GombeCreditLogger.e(">>>>>>>>>>main>>>>>>>>>>>sub event："+event.eventType)
        when(event.eventType){
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESH -> {//刷新流程
                loadGombeCreditProcessAction()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED -> {//流程刷新完成
                checkGombeCreditMainShowPage()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_PRODUCT_REFRESH -> {//刷新产品列表
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_SHOW_HOME -> {//显示首页
                showGombeCreditMainHomePage()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_SHOW_REPAY -> {//待还款
                showGombeCreditMainMenuPage()
            }
            GombeCreditEventData.TYPE.GOMBECREDIT_SYC_ALL_DEVICE -> {//上报所有设备数据
                GombeCreditLogger.e(">>>>>>>>>>>>>>>>syc device all data ")
                //此通知只会在申贷完成之后发送
                TestDataLibInvoke.takeGombeCreditDeviceInfoTypesAction()
            }
            else -> {

            }
        }
    }

    /**
     * 获取总流程
     */
    private fun loadGombeCreditProcessAction(){
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_PROCESS_PATH)
        }
        doPostAction(httpUrl,params,object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                val obj = data.optJSONObject("obj")
                //保存用户流程状态
                if (obj != null) {
                    // TODO: 测试添加 Step 类型
//                    val allStepTitles = obj.optJSONArray("allStepTitles")
//                    allStepTitles.put("Account Info")
//                    allStepTitles.put("Ocr Info")
//                    allStepTitles.put("Face recognition")
//                    val allSteps = obj.optJSONArray("allSteps")
//                    allSteps.put("account_info")
//                    allSteps.put("ocr_info")
//                    allSteps.put("sefie_info")
//                    val steps = obj.optJSONArray("steps")
//                    steps.put("account_info")
//                    steps.put("sefie_info")
//                    steps.put("ocr_info")
//                    val index = Random.nextInt(3)
//                    when(index){
//                        0 -> {
//                            steps.put("ocr_info")
//                        }
//                        1 -> {
//                            steps.put("sefie_info")
//                        }
//                        else -> {
//                            steps.put("account_info")
//                        }
//                    }
                    //保存用户流程数据
                    GombeCreditProcessHelper.saveGombeCreditProcessData(obj)
                    //通知全局流程刷新完成
                    publishEventData(GombeCreditEventData(GombeCreditEventData.TYPE.GOMBECREDIT_PROCESS_REFRESHED))

                    // TODO: 2024-11-20 新增需求 此处需要判断是否需要校验手机号
                    if (GombeCreditProcessHelper.isGombeCreditCheckWhatsApp() || GombeCreditProcessHelper.isGombeCreditCheckSMS()){
                        showGombeCreditMainMustCheckMobilePage()
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
            }

            override fun onRequestFinish() {
            }
        })
    }
}